<?php
namespace Common\Mysql;
class AdvertiseMysql extends CommonMysql {

    public function addAdvertise($data) {
        $code = v($data,'code');
        verify($code,'notEmpty','广告标识不能为空');
        verify($code,'isAdvertiseCode','非法广告标识');

        $sid = v($data,'sid');
        verify($sid,'notEmpty','网站ID不能为空');
        verify($sid,'isID','非法网站ID');

        $html = v($data,'html');
        verify($html,'notEmpty','广告代码不能为空');

        $expireday = v($data,'expireday',0,true);
        $expiretime = $expireday ? NOW_TIME + $expireday * 86400 : 0;

        $status = v($data,'status',1,true);
        verify($status,'isStatus','非法状态');

        if($this->where("`code`='{$code}' AND `sid` = '{$sid}'")->count()) {
            E('广告已经存在');
        }

        $siteInfo = M('Site')->find($sid);;
        verify($siteInfo,'notEmpty','网站不存在');
    
        $id = $this->addRecord(array(
            'code'      =>  $code,
            'sid'       =>  $sid,
            'html'      =>  $html,
            'createtime'=>  NOW_TIME,
            'expiretime'=>  $expiretime,
            'status'    =>  $status,
        ),false,'广告添加失败');

        return $id;
    }

    public function updateAdvertise($data) {
        $id = v($data,'id');
        verify($id,'notEmpty','广告ID不能为空');
        verify($id,'isID','非法广告ID');

        $code = v($data,'code');
        verify($code,'notEmpty','广告标识不能为空');

        $sid = v($data,'sid');
        verify($sid,'notEmpty','网站ID不能为空');
        verify($sid,'isID','非法网站ID');

        $html = v($data,'html');
        verify($html,'notEmpty','广告代码不能为空');

        $status = v($data,'status',1,true);
        verify($status,'isStatus','非法状态');

        if($this->where("`code`='{$code}' AND `sid` = '{$sid}' AND `id` <> {$id}")->count()) {
            E('广告已经存在');
        }

        $siteInfo = M('Site')->find($sid);;
        verify($siteInfo,'notEmpty','网站不存在');
    
        $update_data = array(
            'id'        =>  $id,
            'code'      =>  $code,
            'sid'       =>  $sid,
            'html'      =>  $html,
            'status'    =>  $status,
        );

        $expireday = v($data,'expireday');
        if(verify($expireday,'isNumber')) {
            $update_data['expiretime'] = $expireday ? NOW_TIME + $expireday * 86400 : 0;
        }

        $id = $this->updateRecord($update_data,false,'广告修改失败');

        return $id;
    }

}
?>
